<template>
  <div class="roles">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-button type="primary" plain>添加角色</el-button>
    <el-table border class="mt-15" :data="roleList" style="width: 100%">
      <el-table-column type="expand">
        <template #default="scope">
          <el-row
            v-for="firstChildren in scope.row.children"
            :key="firstChildren.id"
          >
            <!-- 左边  第一层权限显示 -->
            <el-col :span="4">
              最左边
              <el-tag
                closable
                @close="deleteRight(scope.row, firstChildren.id)"
                >{{ firstChildren.authName }}</el-tag
              >
              <i
                class="el-icon-arrow-right"
                v-if="firstChildren.children.length !== 0"
              ></i>
            </el-col>

            <el-col :span="20">
              <el-row
                v-for="secondChildren in firstChildren.children"
                :key="secondChildren.id"
              >
                <el-col :span="4">
                  中间
                  <el-tag
                    closable
                    type="success"
                    @close="deleteRight(scope.row, secondChildren.id)"
                    >{{ secondChildren.authName }}</el-tag
                  >
                  <i
                    class="el-icon-arrow-right"
                    v-if="secondChildren.children.length !== 0"
                  ></i>
                </el-col>

                <el-col :span="20"
                  >右边
                  <el-tag
                    @close="deleteRight(scope.row, thirdChildren.id)"
                    closable
                    type="warning"
                    v-for="thirdChildren in secondChildren.children"
                    :key="thirdChildren.id"
                  >
                    {{ thirdChildren.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row v-if="scope.row.children.length === 0">
            <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <!--  编辑 -->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <el-button
              size="small"
              @click="handleEdit(scope.$index, scope.row)"
            >
              <el-icon>
                <EditPen />
              </el-icon>
            </el-button>
          </el-tooltip>

          <!-- 删除 -->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </el-tooltip>

          <!-- 分配 -->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="分配权限"
            placement="top"
          >
            <el-button
              size="mini"
              type="warning"
              plain
              @click="showGrantDialog(scope.$index, scope.row)"
            >
              <el-icon><Select /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--   权限列表弹框 -->

  <el-dialog title="授权角色" v-model="dialogFormVisibleRoles">
    <div class="tree-container">
      <el-tree
        :data="dataRightsList"
        show-checkbox
        ref="treeRef"
        node-key="id"
        default-expand-all
        :default-checked-keys="selectedRights"
        :props="defaultProps"
      >
      </el-tree>
    </div>
    <template #footer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleRoles = false">取 消</el-button>
        <el-button type="primary" @click="submitRights">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'

import { getRolesApi } from '@/api/user'

import { deleteRoleRight, getRightList, grantRoleRight } from '@/api/rights'

import { Timer, Select, Delete, EditPen } from '@element-plus/icons-vue'

const roleList = ref([])

const isLoading = ref(false)

const getRoles = async () => {
  let res = await getRolesApi()

  console.log(res.data)

  roleList.value = res.data
}

onMounted(() => {
  getRoles()
})

const handleDelete = async (index, row) => {}

const handleEdit = async (index, row) => {}

// 分配权限
// 1 打开弹框
// 2 展示 el-tree 组件
// 3  勾选 节点
// 4  如何获取 已经选中的节点？
// 5   点击确定按钮  关闭弹框 进行授权分配
//  6  成功后 重新 更新当前用户的权限 列表

const dialogFormVisibleRoles = ref(false)

const defaultProps = {
  children: 'children',
  label: 'authName',
}

const dataRightsList = ref([])
const treeRef = ref(null)

const selectedRights = ref([]) // 默认选中的节点

let roleId = ref(null)

const checkNode = (node, arr) => {
  if (!node.children) {
    return arr.push(node.id)
  }

  node.children.forEach((item) => {
    console.log('item', item)
    return checkNode(item, arr)
  })
}

const showGrantDialog = async (index, row) => {
  let res = await getRightList({ type: 'tree' })

  console.log('row1', row)
  roleId.value = row.id // 每次打开弹框的时候获取用户的id

  dataRightsList.value = res.data

  // 每次打开之前 初始化选中的数组 保证这个数组是一个空数组

  selectedRights.value.length = 0
  // selectedRights.value = []

  dialogFormVisibleRoles.value = true

  checkNode(row, selectedRights.value)
}

//  点击确定按钮 需要获取到勾选的节点

const submitRights = async () => {
  let CheckedAllKeys = treeRef.value.getCheckedKeys() // 当前选中的节点

  console.log(CheckedAllKeys, 'CheckedAllKeys')
  let checkedHalfKeys = treeRef.value.getHalfCheckedKeys() // 获取到当前半选中的节点
  console.log(checkedHalfKeys, 'checkedHalfKeys')

  //  全部选中 和半选中  包含之前已经有的权限

  const all = [...CheckedAllKeys, ...checkedHalfKeys]
  console.log(all)
  // 发送请求
  let ridsStr = all.join(',')

  let res = await grantRoleRight({ roleId: roleId.value, rids: ridsStr })
  console.log(res.data)
  dialogFormVisibleRoles.value = false

  getRoles()
}

// 删除角色的制定权限
// row  表示当前这一项   里面包含了 当前用户 角色 id
// rightId 表示权限id

const deleteRight = (row, rightId) => {
  deleteRoleRight({ roleId: row.id, rightId: rightId }).then((res) => {
    // getRoles() // 发送请求
    row.children = res.data // 不需要发送请求
  })
}
</script>

<style lang="scss" scoped>
.roles {
  .el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  .tree-container {
    height: 300px;
    overflow: auto;
  }
}
</style>
